import { PlusOutlined } from '@ant-design/icons'
import { Button, Form, Input, Radio, Select, Space, Upload, message } from 'antd'
import 'quill/dist/quill.snow.css'
import { useEffect, useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { articleGetArticleDetail, articlePublishArticle, articleUpdateArticle } from '../../apis/article'
import BreadCrumb from "../../components/BreadCrumb"
import RichEditor from '../../components/RichEditor'
import { useChannel } from '../../hooks/useChannel'
import './index.scss'

const { Option } = Select
const Publish = () => {
  const [imageList, setImageList] = useState([])
  const [imageType, setImageType] = useState(1)
  const [form] = Form.useForm()
  const [articleContent, setArticleContent] = useState('')
  const navigate = useNavigate()
  // 获取子组件传递的方法
  let setRichContet = null
  const getChildrenWay = (way) => {
    setRichContet = way
  }
  // 获取频道列表数据
  const { channelList } = useChannel()
  // 提交表单，获取表单内容
  const onFinish = async (formVal) => {
    const { title, content, channel_id } = formVal
    const repData = {
      title,
      content,
      cover: {
        type: imageType,
        images: imageList.map(item => {
          if (item.response) {
            return item.response.data.url
          } else {
            return item.url
          }
        })
      },
      channel_id
    }
    // 校验封面图片数量与用户选择的是否一致
    if (imageList.length !== imageType) return message.error('上传的图片数量不足')
    let res = null
    if (articleId) {
      res = await articleUpdateArticle(articleId, repData)
    } else {
      res = await articlePublishArticle(repData)
    }

    if (res.data.message === 'OK') {
      message.success(articleId ? '修改文章成功' : '发布文章成功')
      // 重置form表单数据
      form.setFieldsValue({
        content: '',
        title: '',
        channel_id: null
      })
      setImageList([])
      setImageType(1)
      setRichContet('')
    }
    // 文章修改完成跳转到文章管理页
    if (articleId) navigate('/article')
  }
  // 图片上传的回调
  const handleChange = (value) => {
    setImageList(value.fileList)
  }
  // 图片上传数量选择的回调
  const ImageTypeChange = (value) => {
    setImageType(value.target.value)
    if (value.target.value === 0) {
      setImageList([])
    }
  }
  // 获取子组件传递的方法


  // 
  const [searchParams] = useSearchParams()
  const articleId = searchParams.get('id')
  useEffect(() => {

    if (articleId) {
      // 根据文章id获取文章详情
      const getArticle = async () => {
        const { data: { data: result } } = await articleGetArticleDetail(articleId)
        // 进行数据回显
        if (result) {
          setArticleContent(result.content)
          setRichContet(result.content)
          setImageType(result.cover.type)
          setImageList(result.cover.images.map(item => { return { url: item } }))
          form.setFieldsValue({
            content: result.content,
            title: result.title,
            channel_id: result.channel_id
          })

        }
      }
      getArticle()
    }
  }, [form, articleId, setRichContet])
  return (
    <div className='publish'>
      {/* 顶部面包屑导航 */}
      <BreadCrumb title={articleId ? '编辑文章' : '发布文章'} />
      <div className="form-container">
        <Form
          form={form}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          onFinish={onFinish}
        >
          <Form.Item name="title" label="标题" rules={[{ required: true, message: '请输入文章标题' }]}>
            <Input placeholder="请输入文章标题" />
          </Form.Item>
          <Form.Item
            name="channel_id"
            label="频道"
            rules={[{ required: true, message: '请选择文章频道' }]}>
            <Select
              placeholder="请选择文章频道"
              allowClear
            >
              {channelList.map(item => <Option key={item.id} value={item.id}>{item.name}</Option>)}
            </Select>
          </Form.Item>
          {/* 图片上传 */}
          <Form.Item label='封面'>
            <Radio.Group
              style={{ marginBottom: '10px' }}
              value={imageType}
              onChange={ImageTypeChange}
              options={[
                { value: 1, label: '单图' },
                { value: 3, label: '三图' },
                { value: 0, label: '无图' },
              ]}
            />
            <Upload
              name='image'
              action="http://geek.itheima.net/v1_0/upload"
              listType="picture-card"
              fileList={imageList}
              showUploadList
              onChange={handleChange}
            >
              {imageList.length >= imageType ? null : <div style={{ marginTop: 8 }}>
                <PlusOutlined />
              </div>}
            </Upload>
          </Form.Item>
          <Form.Item
            label='内容'
            name='content'
          >
            {/* 富文本编辑器 */}
            <RichEditor deliveryWay={getChildrenWay} value={articleContent} />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                {articleId ? '修改文章' : '发布文章'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
    </div >
  )
}
export default Publish